import json
import datetime
from datetime import datetime as dt
import tkinter.messagebox

import time
import tkinter
from tkinter import ANCHOR, Text, RAISED, END

import requests
from bs4 import BeautifulSoup

from tkinter.ttk import *

from config.days_config import days


def get_dat(u_title=None):
    last_send = []
    if u_title:
        weekday = dt.strptime(u_title, "%Y-%m-%d").weekday()
    else:
        weekday = dt.now().weekday()
    if weekday == 0:
        _apd = "HI 搬砖人 【 今日周一 距离周末还有：4天 】"
        _a1 = "新的一周又开始了，新的压力又将降临。"
        _a2 = "有压力是好事，能够鞭策我们努力前行。"
        _a3 = "人生就是这样，没有如果，只有结果。"
        _a4 = "没有回头，只有往前走，一起加油!"
        _apc = "有事没事起身去茶水间，去厕所，去廊道走走。"
        _apcd = "别老在工位上坐着，钱是老板的，但命是自己的。"
        last_send.append(_apd)
        last_send.append("---------------------------")
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
        last_send.append(_apc)
        last_send.append(_apcd)
    elif weekday == 1:
        _apd = "HI 搬砖人 【 今日周二 距离周末还有：3天 】"
        _a1 = "惟有心怀光亮望向远方"
        _a2 = "才能看见幸福真正的模样"
        _a3 = "真正拥抱自己"
        _a4 = "更好的生活，正在前方等着你！"
        _apc = "有事没事起身去茶水间，去厕所，去廊道走走。"
        _apcd = "别老在工位上坐着，钱是老板的，但命是自己的。"
        last_send.append(_apd)
        last_send.append("---------------------------")
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
        last_send.append(_apc)
        last_send.append(_apcd)
    elif weekday == 2:
        _apd = "HI 搬砖人 【 今日周三 距离周末还有：2天 】"
        _a1 = "周三了，希望你有三头六臂，轻松完成工作。"
        _a2 = "三拳两脚，轻松打败困难。"
        _a3 = "吾日三省吾身，明白生活的意义。"
        _a4 = "三思而行，深思熟虑好好处理事情。"
        _a5 = "等周末再见你，定要让我刮目相看！"
        _apc = "有事没事起身去茶水间，去厕所，去廊道走走。"
        _apcd = "别老在工位上坐着，钱不是你的，但命是自己的。"
        last_send.append(_apd)
        last_send.append("---------------------------")
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
        last_send.append(_a5)
        last_send.append(_apc)
        last_send.append(_apcd)
    elif weekday == 3:
        _apd = "HI 搬砖人 【 今日周四 距离周末还有：1天 】"
        _a1 = "保留再多，也是一种缺失；"
        _a2 = "播撒多了，才会拥有。"
        _a3 = "吾日三省吾身，明白生活的意义。"
        _a4 = "三有舍才有得，与其有所保留，不如大方给予。"
        _a5 = "浇灌万物的同时，也浇灌了自己。"
        _apc = "有事没事起身去茶水间，去厕所，去廊道走走。"
        _apcd = "别老在工位上坐着，钱不是你的，但命是自己的。"
        last_send.append(_apd)
        last_send.append("---------------------------")
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
        last_send.append(_a5)
        last_send.append(_apc)
        last_send.append(_apcd)
    elif weekday == 4:
        _apd = "HI 搬砖人 【 今日周五 明天就是周末了！】"
        _a1 = "周一虐我千百遍，我待周五如初恋。"
        _a2 = "工作烦恼抛一边，快快乐乐似神仙。"
        _a3 = "三五朋友聚一聚，凑到一起不容易。"
        _a4 = "愿君有个愉快的周末!"
        _apc = "有事没事起身去茶水间，去厕所，去廊道走走。"
        _apcd = "别老在工位上坐着，钱不是你的，但命是自己的。"
        last_send.append(_apd)
        last_send.append("---------------------------")
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
        last_send.append(_apc)
        last_send.append(_apcd)
    elif weekday == 5:
        last_send.append("HI 搬砖人 【周末愉快】")
        last_send.append("---------------------------")
        _a1 = "周末又到，让太阳去早起，自己睡到笑。"
        _a2 = "让乌云去沉重，自己心情轻飘飘。"
        _a3 = "让风去匆忙，自己一边看风景，一边慢慢挪着脚"
        _a4 = "这是你的时间，尽情享受生活吧!"
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
    elif weekday == 6:
        last_send.append("HI 搬砖人 【周末愉快】")
        last_send.append("---------------------------")
        _a1 = "周末又到，让太阳去早起，自己睡到笑。"
        _a2 = "让乌云去沉重，自己心情轻飘飘。"
        _a3 = "让风去匆忙，自己一边看风景，一边慢慢挪着脚"
        _a4 = "这是你的时间，尽情享受生活吧!"
        last_send.append(_a1)
        last_send.append(_a2)
        last_send.append(_a3)
        last_send.append(_a4)
    last_send.append("---------------------------")
    for i in days:
        timeStamp = int(time.mktime(time.strptime(i.get("date"), "%Y-%m-%d")))
        if u_title:
            today = int(time.mktime(time.strptime(u_title, "%Y-%m-%d")))
        else:
            today = int(time.mktime(time.strptime(datetime.date.today().strftime("%Y-%m-%d"), "%Y-%m-%d")))
        day = (timeStamp - today) // (24 * 60 * 60)
        is_work = i.get("isWorkDay")
        strs = "距离【%s】 还有：%d天 %s" % (i.get("name"), day, "工作 " if is_work == 1 else "放假")
        if not str(day).startswith("-"):
            if day == 0:
                strss = "今天是%s 哟 祝你节日快乐" % (i.get("name"))
                last_send.append(strss)
            if i.get("important") == 1:
                last_send.append(strs)
    last_send.append("---------------------------")
    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
    _last_content2 = "关注我，这样每天我都能见到你了"
    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
    _last_content4 = "========Email:henry_oulen@163.com======="

    last_send.append(last_content)
    last_send.append(_last_content)
    last_send.append(_last_content0)
    last_send.append(_last_content1)
    # last_send.append("---------------------------")
    # last_send.append(_last_content2)
    # last_send.append(_last_content3)
    content = json.dumps(last_send, ensure_ascii=False)
    #     #      综合   科技   娱乐    社区        购物      财经
    #     #page=['news','tech','ent','community','shopping','finance']
    # page = ['news']
    # try:
    #     for tag in page:
    #         url = 'https://tophub.today/c/{}'.format(tag)
    #         html = download_page(url)
    #         return_list = get_content(html, tag)
    #         last_send = last_send + return_list
    # except Exception as e:
    #     pass
    last_send.append("---------------------------")
    last_send.append(_last_content2)
    last_send.append(_last_content3)
    last_send.append(_last_content4)

    return last_send


def download_page(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"}
    try:
        r = requests.get(url, timeout=30, headers=headers)
        return r.text
    except:
        return "please inspect your url or setup"


def get_content(html, tag, _v):
    soup = BeautifulSoup(html, 'html.parser')
    con = soup.find('div', attrs={'class': 'bc-cc'})
    con_list = con.find_all('div', class_="cc-cd")
    return_list = []
    for i in con_list:
        num = []
        title = []
        hot = []
        href = []
        author = i.find('div', class_='cc-cd-lb').get_text()  # 获取平台名字
        if _v == "hot":
            if str(author.strip()) == "百度":
                _str = "------------%s--------------" % ("百度实时热榜" if author.strip() == "百度" else author.strip())
                return_list.append(_str)
                _num = 0
                link = i.find('div', class_='cc-cd-cb-l').find_all('a')  # 获取所有链接
                for k in link:
                    href.append(k['href'])
                    num.append(k.find('span', class_='s').get_text())
                    title.append(str(k.find('span', class_='t').get_text()))
                    hot.append(str(k.find('span', class_='e').get_text()))
                for h in range(len(num)):
                    _num += 1
                    _temp_str = "%s.%s" % (num[h], title[h])
                    return_list.append(_temp_str)
        elif _v == "today":
            if str(author.strip()) == "历史上的今天":
                _str = "------------%s--------------" % ("百度热榜" if author.strip() == "百度" else author.strip())
                return_list.append(_str)
                _num = 0
                link = i.find('div', class_='cc-cd-cb-l').find_all('a')  # 获取所有链接
                for k in link:
                    href.append(k['href'])
                    num.append(k.find('span', class_='s').get_text())
                    title.append(str(k.find('span', class_='t').get_text()))
                    hot.append(str(k.find('span', class_='e').get_text()))
                for h in range(len(num)):
                    _num += 1
                    _temp_str = "%s.%s" % (num[h], title[h])
                    return_list.append(_temp_str)
    return return_list


def save_txt(tag, *args):
    for i in args:
        with open(tag + '.txt', 'a', encoding='utf-8') as f:
            f.write(i)


def say_hello():
    last_send = get_dat()
    send = ""
    for i in last_send:
        send += i + "\r\n"
    tkinter.messagebox.showinfo(title='my message', message=send)


def get_today():
    last_send = []
    #     #      综合   科技   娱乐    社区        购物      财经
    #     #page=['news','tech','ent','community','shopping','finance']
    page = ['news']
    _v = "today"
    try:
        for tag in page:
            url = 'https://tophub.today/c/{}'.format(tag)
            html = download_page(url)
            return_list = get_content(html, tag, _v)
            last_send = last_send + return_list
    except Exception as e:
        pass
    last_send.append("---------------------------")
    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
    _last_content2 = "关注我，这样每天我都能见到你了"
    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
    _last_content4 = "========Email:henry_oulen@163.com======="

    last_send.append(last_content)
    last_send.append(_last_content)
    last_send.append(_last_content0)
    last_send.append(_last_content1)
    last_send.append(_last_content2)
    last_send.append(_last_content3)
    last_send.append(_last_content4)
    send = ""
    for i in last_send:
        send += i + "\r\n"
    tkinter.messagebox.showinfo(title='my message', message=send)


def get_hot_news():
    #     #      综合   科技   娱乐    社区        购物      财经
    #     #page=['news','tech','ent','community','shopping','finance']
    page = ['news']
    last_send = []
    _v = "hot"
    try:
        for tag in page:
            url = 'https://tophub.today/c/{}'.format(tag)
            html = download_page(url)
            return_list = get_content(html, tag, _v)
            last_send = last_send + return_list
    except Exception as e:
        pass
    last_send.append("---------------------------")
    last_content = "认认真真上班，这根本就不叫赚钱，那是用劳动换取报酬。"
    _last_content = "人活半辈子才明白，真正高级的养生，是回家好好吃饭"
    _last_content0 = "别沮丧，生活就像心电图，一帆风顺就证明你挂了！"
    _last_content1 = "最后，祝愿天下所有摸鱼人，都能愉快的渡过每一天!"
    _last_content2 = "关注我，这样每天我都能见到你了"
    _last_content3 = "我是 【捣蛋小能手】 捣蛋的捣 & 捣蛋的蛋 ! "
    _last_content4 = "========Email:henry_oulen@163.com======="

    last_send.append(last_content)
    last_send.append(_last_content)
    last_send.append(_last_content0)
    last_send.append(_last_content1)
    last_send.append(_last_content2)
    last_send.append(_last_content3)
    last_send.append(_last_content4)
    send = ""
    for i in last_send:
        send += i + "\r\n"
    tkinter.messagebox.showinfo(title='my message', message=send)


def cal2(event):
    if t1.get():
        need_time = t1.get().strip()
        time_local = time.localtime(int(need_time))  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        comb3.delete('1.0', END)
        comb3.insert(END, "\n", "center")  # ADDED
        comb3.insert(END, "           " + str(time_format), "center")
    else:
        now_time = int(time.time())
        time_local = time.localtime(now_time)  # 转化成localtime
        time_format = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
        comb3.delete('1.0', END)
        comb3.insert(END, "\n", "center")  # ADDED
        comb3.insert(END, "           " + str(time_format), "center")


def cal3(event):
    if t2.get():
        formate_data = t2.get().strip()
        if len(formate_data) == 10:
            # 转换成时间数组
            time_array = time.strptime(formate_data, "%Y-%m-%d")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            comb3.delete('1.0', END)
            comb3.insert(END, "\n", "center")  # ADDED
            comb3.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 19:  # "2023-03-21 15:11:25"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M:%S")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            comb3.delete('1.0', END)
            comb3.insert(END, "\n", "center")  # ADDED
            comb3.insert(END, "                    " + str(time_format), "center")
        elif len(formate_data) == 16:  # "2023-04-01 14:00"
            time_array = time.strptime(formate_data, "%Y-%m-%d %H:%M")
            # 转换成时间戳
            time_format = int(time.mktime(time_array))
            comb3.delete('1.0', END)
            comb3.insert(END, "\n", "center")  # ADDED
            comb3.insert(END, "                    " + str(time_format), "center")
    else:
        now_time = int(time.time())
        comb3.delete('1.0', END)
        comb3.insert(END, "\n", "center")  # ADDED
        comb3.insert(END, "                    " + str(now_time), "center")  # ADDED


def listbox_copy(event):
    window.clipboard_clear()
    selected = comb3.get(ANCHOR)
    selected = selected.strip()
    window.clipboard_append(selected)


def copy_to_clipboard():
    """Copy current contents of text_entry to clipboard."""
    window.clipboard_clear()  # Optional.
    window.clipboard_append(comb3.get('1.0', END).rstrip().strip())


def gettime():
    timestr = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')  # 获取当前的时间并转化为字符串
    lb.configure(text=timestr)  # 重新设置标签文本
    window.after(100, gettime)  # 每隔1s调用函数 gettime 自身获取时间


def gettime_month():
    timestr = datetime.datetime.now().weekday()  # 获取当前的时间并转化为字符串
    date_dict = {
        0: "星期一",
        1: "星期二",
        2: "星期三",
        3: "星期四",
        4: "星期五",
        5: "星期六",
        6: "星期日",
    }
    timestr = date_dict.get(timestr)
    lb_1.configure(text=timestr)  # 重新设置标签文本
    window.after(1000 * 60, gettime)  # 每隔1s调用函数 gettime 自身获取时间


window = tkinter.Tk()
window.attributes("-topmost", True)
width = window.winfo_screenwidth()
window.title('小工具')
window.geometry('472x792')

lb = tkinter.Label(window, text='', fg='black', font="等线 20 bold")
lb.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.1)
gettime()

lb_1 = tkinter.Label(window, text='', fg='black', font="等线 20 bold")
lb_1.place(relx=0.1, rely=0.02, relwidth=0.8, relheight=0.1)
gettime_month()

lbl1 = Label(window, text='时间戳', font="等线 16 bold")
lbl1.place(relx=0.1, rely=0.2, relwidth=0.2, relheight=0.1)
t1 = Entry(window, font="等线 16 bold", )
t1.place(relx=0.1, rely=0.3, relwidth=0.4, relheight=0.1)

lbl2 = Label(window, text='时间格式', font="等线 16 bold")
lbl2.place(relx=0.5, rely=0.2, relwidth=0.2, relheight=0.1, )
t2 = Entry(window, font="等线 16 bold", justify="center", )
t2.place(relx=0.5, rely=0.3, relwidth=0.4, relheight=0.1)

comb1 = tkinter.Button(window, text="时间戳-->格式化", command="cal2", activeforeground="red", font="等线 16 bold")
comb1.bind("<Button-1>", cal2)
comb1.place(relx=0.1, rely=0.4, relwidth=0.4, relheight=0.1)

comb2 = tkinter.Button(window, text="时间格式-->时间戳", command="cal3", activeforeground="red", font="等线 16 bold")
comb2.bind("<Button-1>", cal3)
comb2.place(relx=0.5, rely=0.4, relwidth=0.4, relheight=0.1)

comb3 = tkinter.Text(window, width=40, height=10, border=4, relief=RAISED, font="等线 16 bold", )
comb3.place(relx=0.1, rely=0.5, relwidth=0.8, relheight=0.1)

clp = tkinter.Button(window, text="复制到粘贴板",
                     command=copy_to_clipboard, activeforeground="red", font="等线 16 bold")
clp.place(relx=0.1, rely=0.6, relwidth=0.8, relheight=0.1)

# 定义消息对话框
b = tkinter.Button(window, padx=5, activeforeground="red", text="节日倒数", command=say_hello, font="等线 16 bold")
b.pack()
b.place(relx=0.1, rely=0.8, relwidth=0.2, relheight=0.1)

c = tkinter.Button(window, padx=5, activeforeground="red", text="今日热榜", command=get_hot_news, font="等线 16 bold")
c.pack()
c.place(relx=0.4, rely=0.8, relwidth=0.2, relheight=0.1)

a = tkinter.Button(window, padx=5, activeforeground="red", text="历史今天", command=get_today, font="等线 16 bold")
a.pack()
a.place(relx=0.7, rely=0.8, relwidth=0.2, relheight=0.1)

window.mainloop()
